package cn.lyjuan.android.demofive.chapter12.app_12_2_5_1;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by chad on 16-1-9.
 */
public class TumblerActivity extends Activity implements SensorEventListener
{
    private GSensitiveView gsView;
    private SensorManager sm;
    private double roration;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        super.onCreate(savedInstanceState);

        gsView = new GSensitiveView(this);
        setContentView(gsView);

        sm = (SensorManager) this.getSystemService(SENSOR_SERVICE);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run()
            {
                updateGUI();
            }
        }, 0, 200);
    }

    @Override
    protected void onResume()
    {
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

        super.onResume();
    }


    @Override
    protected void onPause()
    {
        sm.unregisterListener(this);

        super.onPause();
    }

    public void updateGUI()
    {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
                gsView.setRotation(TumblerActivity.this.roration);
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent event)
    {
        if (Sensor.TYPE_ACCELEROMETER != event.sensor.getType()) return;

        float[] values = event.values;
        float ax = values[0];
        float ay = values[1];

        double g = Math.sqrt(ax * ax + ay * ay);
        double cos = ay / g;

        if (cos > 1)
        {
            cos = 1;
        } else if (cos < -1)
        {
            cos = -1;
        }

        double rad = Math.acos(cos);
        if (ax < 0)
        {
            rad = 2 * Math.PI - rad;
        }

        int uiRot = getWindowManager().getDefaultDisplay().getRotation();
        double uiRad = Math.PI / 2 * uiRot;

        rad -= uiRad;

        this.roration = rad;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}
